﻿<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.IO;
using System.Collections.Generic;

using EHSubmit.Logic;
using EHSubmit.Logic.Relationship;
using EHSubmit.Model;
using EHSubmit.Util;

public class UploadHandler : BaseAjaxHandler
{
    protected override void Mapping()
    {
        OprationMap["listGoals"] = "ListGoals";         // 列出可选(需要提交)的作业
        OprationMap["listCourses"] = "ListCourses";     // 列出可选(需要提交)的作业
        OprationMap["addWork"] = "AddHomeWork";         // 提交作业（学生）
        OprationMap["addGoal"] = "AddGoal";             // 布置作业（教师）
    }

    public void ListGoals()
    {
        if (Validate(ERole.Student))
        {
            IRelationshipManager manager = RelationshipFactory.GetInstance();
            /// 根据学生ID,取需要提交的作业
            /// 
            IList<EHSubmit.Model.Goal> goals = manager.GetGoalsOfStudent(CurrentUser.ID);

            string jsonGoals = JsonHelper.Serialize(goals);

            int count = goals.Count;

            IsSuccess = true;

            ResponseText = "{" + string.Format("count:{0},data:{1}", count, jsonGoals) + "}";
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
    }
    
    
    
    /// <summary>
    /// 添加作业
    /// </summary>
    public void AddHomeWork()
    {
        if (Validate(ERole.Student))
        {
            try
            {
                int goalId = int.Parse(Context.Request["goalId"]);

                // 获得上传请求中的文件（单个文件）
                HttpPostedFile postedFile = Context.Request.Files[0];
                string fileName = postedFile.FileName;                   // 取得文件名
                string ext = System.IO.Path.GetExtension(fileName);      // 获得后缀名
                
                // 获得Goal实例,布置作业的信息
                GoalManager gManager = new GoalManager();
                EHSubmit.Model.Goal goal = gManager.GetGoal(goalId);
                
                //if (!goal.AllowedFileTypes.Contains(ext){
                //     throw new Exception("只能传输的文件格式为:" + goal.AllowedFileTypes);  
                //}

                string reqstGoalPath = FileHelper.GenerateGoalPath(CurrentUser, goal);    // 将要上传的虚拟目录
                string realGoalPath = Context.Server.MapPath(reqstGoalPath);              // 上传的物理目录
                string attachFileName = FileHelper.GenerateFileName(CurrentUser, ext);

                string attachPath = realGoalPath + attachFileName; // 文件物理地址

                
                // 创建目录
                if (!Directory.Exists(realGoalPath))
                {
                    Directory.CreateDirectory(realGoalPath);
                }
                //保存文件
                postedFile.SaveAs(attachPath);
                
                // 生成作业实例
                Homework hmwork = new Homework();
                hmwork.Description = Context.Request["description"];
                hmwork.GoalName = Context.Request["goalTitle"];
                hmwork.AttachPath = reqstGoalPath + attachFileName;         // 这里不将物理地址存入库,在列表时要通过JSON读AttachPath字段,使用物理地址可能不安全,将虚拟地址入库
                hmwork.GoalID = goalId;
                hmwork.StudentID = CurrentUser.ID;
                hmwork.SubmitTime = DateTime.Now;
                hmwork.UpdateTime = hmwork.SubmitTime;
                hmwork.Term = ConfigHelper.GetTerm();   // TODO   暂时根据配置文件获得当前学期，本应根据教务处同步，待处理。
                hmwork.Scores = -1;     // -1标志没有成绩
                
                //添加
                HomeworkManager manager = new HomeworkManager();
                manager.AddHomework(hmwork);
                
                
                IsSuccess = true;
                ResponseText ="{success:true,msg:'添加成功！'}";
            }
            catch (Exception e)
            {
                LogHelper.Log(e.Message, e);
                
                Message = e.Message;
            }
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
        
    }



    /// <summary>
    /// 列出教师所授课程
    /// </summary>
    public void ListCourses()
    {
        IRelationshipManager manager = RelationshipFactory.GetInstance();

        IList<Course> courses = manager.GetCoursesOfTeacher(CurrentUser.ID);

        int count = courses.Count;
        string jsonCourses = JsonHelper.Serialize(courses);
        
        IsSuccess = true;
        ResponseText = "{" + string.Format("count:{0},data:{1}", count, jsonCourses) + "}";
    }
    
    /// <summary>
    /// 布置作业
    /// </summary>
    public void AddGoal()
    {
        if (Validate(ERole.Teacher))
        {

            try
            {

                string courseId = Context.Request["courseId"];
                string goalTitle = Context.Request["goalTitle"];
                string deadline = Context.Request["deadline"];
                string description = Context.Request["description"];

                // 获得上传请求中的文件（单个文件）
                HttpPostedFile postedFile = Context.Request.Files[0];
                string fileName = postedFile.FileName;                   // 取得文件名
                string ext = System.IO.Path.GetExtension(fileName);      // 获得后缀名

                // 限制只能上传的文件类型,防止恶意上传
                //....

                // 设置路径
                string reqstGoalPath = FileHelper.GenerateAttachPath(CurrentUser);        // 将要上传的虚拟目录
                string realGoalPath = Context.Server.MapPath(reqstGoalPath);              // 上传的物理目录
                string attachFileName = FileHelper.GenerateAttachFileName(goalTitle, ext);

                string attachPath = realGoalPath + attachFileName; // 文件物理地址


                // 创建目录
                if (!Directory.Exists(realGoalPath))
                {
                    Directory.CreateDirectory(realGoalPath);
                }
                //保存文件
                postedFile.SaveAs(attachPath);

                // 生成Goal实例
                Goal goal = new Goal();

                goal.AttachPath = reqstGoalPath + attachFileName;
                goal.CourseID = courseId;
                //自定义日期转换
                goal.DeadLine = DateTime.ParseExact(deadline, "yyyy年M月d日", null);
                goal.Description = description;
                goal.FileTypeAllowed = "*.*";  //.. 库表中这个字段如何设置的?
                goal.IsDeleted = false;
                goal.Term = ConfigHelper.GetTerm();
                goal.Title = goalTitle;
                goal.TeacherID = CurrentUser.ID;
                goal.LastSubmitTime = DateTime.Now;
                goal.PublishTime = DateTime.Now;
                //goal.SubYear = DateTime.



                // 添加
                GoalManager manager = new GoalManager();
                manager.AddGoal(goal);

                IsSuccess = true;
                ResponseText = "{success:true, msg:'添加成功！'}";
            }
            catch (Exception e)
            {
                LogHelper.Log(e.Message, e);
                
                Message = e.Message;
            }
            
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
        
    }



}